#include <native_drawing/drawing_shadow_layer.h>
#include <native_drawing/drawing_text_typography.h>
#include "sample_bitmap.h"
#include "log_print.h"

SampleBitMap::~SampleBitMap()
{
    Destroy();
}

void SampleBitMap::SetWidth(uint64_t width)
{
    width_ = width;
}

void SampleBitMap::SetHeight(uint64_t height)
{
    height_ = height;
}

void* SampleBitMap::GetText(void)
{
    // 画完后获取像素地址，地址指向的内存包含画布画的像素数据
    void *bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap_);
    return bitmapAddr;
}

void SampleBitMap::Create(void)
{
    // 创建一个bitmap对象
    cBitmap_ = OH_Drawing_BitmapCreate();
    
    // 定义bitmap的像素格式
    OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_PREMUL};//ALPHA_FORMAT_OPAQUE};
    
    // 构造对应格式的bitmap
    OH_Drawing_BitmapBuild(cBitmap_, width_, height_, &cFormat);

    // 创建一个canvas对象
    cCanvas_ = OH_Drawing_CanvasCreate();
    
    // 将画布与bitmap绑定，画布画的内容会输出到绑定的bitmap内存中
    OH_Drawing_CanvasBind(cCanvas_, cBitmap_);
    
    // 使用白色清除画布内容
    OH_Drawing_CanvasClear(cCanvas_, OH_Drawing_ColorSetArgb(0x0, 0x0, 0x0, 0x0));
}

void SampleBitMap::Destroy(void)
{
    // 销毁canvas对象
    OH_Drawing_CanvasDestroy(cCanvas_);
    cCanvas_ = nullptr;
    
    // 销毁bitmap对象
    OH_Drawing_BitmapDestroy(cBitmap_);
}

void SampleBitMap::DrawText(void)
{
    // 创建字体对象
    OH_Drawing_Font *font = OH_Drawing_FontCreate();
    
    // 设置字体大小
    OH_Drawing_FontSetTextSize(font, 50);
    
    // 获取当前时间
    struct timespec now;
    if (clock_gettime(CLOCK_REALTIME, &now) != 0) {
        LOGE("Failed to get current time.");
        OH_Drawing_FontDestroy(font);
        return;
    }
    time_t seconds = now.tv_sec;

    // 将时间转换为字符串
    char timeStr[126];
    if (ctime_r(&seconds, timeStr) == nullptr) {
        LOGE("Failed to convert time to string.");
        OH_Drawing_FontDestroy(font);
        return;
    }

    // 创建文本块
    OH_Drawing_TextBlob *textBlob = OH_Drawing_TextBlobCreateFromString(
        timeStr, font, OH_Drawing_TextEncoding::TEXT_ENCODING_UTF8);
    if (textBlob == nullptr) {
        LOGE("Failed to create text blob.");
        OH_Drawing_FontDestroy(font);
        return;
    }

    // 绘制字块
    OH_Drawing_CanvasDrawTextBlob(cCanvas_, textBlob, 220, 960);
    
    // 释放字块对象
    OH_Drawing_TextBlobDestroy(textBlob);
    
    // 释放字体对象
    OH_Drawing_FontDestroy(font);
}
